﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QuickApp.Core;
using EfSearchModel.Model;
using QuickApp.MVCControl;
using Resto.CostControl.Core;
using QuickApp.MVCControl.Form;

namespace Resto.CostControl.Web.Controllers
{
    public class SupplierController : Controller
    {
        private readonly IRepository<Supplier> _Repo;
        private readonly IUnitOfWork _UnitOfWork;

        public SupplierController(IRepository<Supplier> repo, UnitOfWork unitOfWork)
        {
            _Repo = repo;
            _UnitOfWork = unitOfWork;
        }

        //
        // GET: /Material/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Index(DWZPageInfo pageInfo, QueryModel where)
        {
            var list = _Repo.GetPageable(pageInfo.ToPageInfo(), where);
            var fdata = pageInfo.ToFlexiGridData<Supplier>(list.Page.ToList(), list.Total);
            return Json(fdata);
        }

        public ActionResult Edit(string Id)
        {
            Supplier data = null;
            if (!string.IsNullOrWhiteSpace(Id))
            {
                data = _Repo.Find(Id);
            }
            else
            {
                data = new Supplier();
            }
            return View(data);
        }

        [HttpPost]
        public JsonResult Save(Supplier data)
        {
            if (ModelState.IsValid)
            {
                if (string.IsNullOrWhiteSpace(data.Id))
                {
                    data.Id = Guid.NewGuid().ToString();
                    _Repo.Insert(data);
                }
                else
                {
                    var oldData = _Repo.Find(data.Id);
                    TryUpdateModel(oldData);
                }

                _UnitOfWork.Commit();
            }

            var result = new JsonReturnMessages
            {
                IsSuccess = true,
                Msg = "操作成功",
            };
            return Json(result);
        }

        [HttpPost]
        public JsonResult Delete(string id)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (!string.IsNullOrEmpty(id))
            {
                try
                {
                    _Repo.Delete(id);
                    _UnitOfWork.Commit();
                    msg.IsSuccess = true;
                    msg.Msg = "操作成功";
                }
                catch
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败,请稍后重试！";
                }
            }
            else
            {
                msg.IsSuccess = false;
                msg.Msg = "参数错误";
            }
            return Json(msg);
        }
    }
}